//
//  Counting.m
//  LockTest
//
//  Created by ZhangBo on 2018/12/2.
//  Copyright © 2018 ZhangBo. All rights reserved.
//

#import "Counting.h"

@interface Counter : NSObject
@property(nonatomic, assign) NSInteger count;
@property(nonatomic, retain) NSLock *lock;

- (void)increment;

- (NSInteger)getCount;
@end


@implementation Counter
- (id)init {
    if (self = [super init]) {
        _count = 0;
        _lock = [[NSLock alloc] init];
    }
    return self;
}

- (void)increment {
    [_lock lock];
    ++_count;
    [_lock unlock];
}

- (NSInteger)getCount {
    return _count;
}
@end

@interface Counting ()
@property(nonatomic, strong) dispatch_queue_t serialQueue;
@end

@implementation Counting
- (id)init {
    if (self = [super init]) {
        _serialQueue = dispatch_queue_create("CONCURRENT", DISPATCH_QUEUE_CONCURRENT);
    }
    return self;
}

- (void)startCounting {
    Counter *counter = [[Counter alloc] init];
    dispatch_async(self.serialQueue, ^{
        for (int i = 0; i < 10000; ++i) {
            [counter increment];
        }
    });

    dispatch_async(self.serialQueue, ^{
        for (int i = 0; i < 10000; ++i) {
            [counter increment];
        }
    });
    dispatch_barrier_async(self.serialQueue, ^{
        NSLog(@"%ld", [counter getCount]);
    });
}
@end

